"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const defines_1 = require("../lib/defines");
const enums_1 = require("../utils/enums");
function offer(app) {
    const { socket, rooms } = app.locals;
    const { userId } = socket.handshake.query;
    socket.on(defines_1.RequestMethod.offer, async function (data, cb) {
        const { clientUtils } = app.locals;
        const { offer, member, room } = data;
        if (!room) {
            return cb && cb({ status: 'error', message: 'room not find!' });
        }
        const __room = rooms[room.classId];
        if (!__room) {
            return cb && cb({ status: 'error', message: 'room not find!' });
        }
        const __member = __room.members[member.userId];
        if (!__member) {
            return cb && cb({ status: 'error', message: 'member not find!' });
        }
        const endpoint = __member.getEndpoint(member.userId);
        let candidatesQueue = __member.candidatesQueue[userId] || (__member.candidatesQueue[userId] = []);
        socket.join(room.classId);
        if (member.userId === userId) {
            if (__room.chatMode === enums_1.ChatModeEnums.BROADCAST && __member.player) {
                await clientUtils.connect(__member.player, endpoint);
                __member.player.play(function (error) {
                    if (error)
                        return;
                });
            }
            clientUtils.processOffer(endpoint, offer, (sdpAnswer) => {
                socket.emit('answer', { sdpAnswer, member });
                console.log('------- joined --------');
                socket.broadcast
                    .to(room.classId)
                    .emit('joined', { member, room });
            });
        }
        else {
            clientUtils.createEndpoint(__member.pipeline, (targetEndpoint) => {
                while (candidatesQueue.length) {
                    const candidate = candidatesQueue.shift();
                    targetEndpoint.addIceCandidate(candidate);
                }
                clientUtils.onIceCandidate(targetEndpoint, (iceCandidate) => {
                    socket.emit('iceCandidate', { iceCandidate, member });
                });
                clientUtils.processOffer(targetEndpoint, offer, async (sdpAnswer) => {
                    if (__room.chatMode === enums_1.ChatModeEnums.BROADCAST && __member.player) {
                        await clientUtils.connect(__member.player, targetEndpoint);
                    }
                    else {
                        clientUtils.connect(endpoint, targetEndpoint);
                    }
                    __member.setEndpoint(userId, targetEndpoint);
                    socket.emit('answer', { sdpAnswer, member });
                });
            });
        }
        if (cb) {
            cb({ status: 'ok', resolve: 'offer' });
        }
    });
}
exports.default = offer;
